<template>
  <div class="api-test-page">
    <van-nav-bar title="API连接测试" left-arrow @click-left="$router.back()" />

    <div class="test-container">
      <h3>🔧 API连接诊断</h3>

      <div class="test-section">
        <h4>基础连接测试</h4>
        <van-button type="primary" @click="testBasicConnection" :loading="testing.basic">
          测试基础连接
        </van-button>
        <div v-if="results.basic" class="test-result">
          <pre>{{ results.basic }}</pre>
        </div>
      </div>

      <div class="test-section">
        <h4>知识问答API测试</h4>
        <van-field v-model="testQuestion" placeholder="输入测试问题" />
        <van-button type="primary" @click="testKnowledgeQA" :loading="testing.qa">
          测试知识问答
        </van-button>
        <div v-if="results.qa" class="test-result">
          <pre>{{ results.qa }}</pre>
        </div>
      </div>

      <div class="test-section">
        <h4>流式API测试</h4>
        <van-button type="primary" @click="testStreamAPI" :loading="testing.stream">
          测试流式输出
        </van-button>
        <div v-if="results.stream" class="test-result">
          <pre>{{ results.stream }}</pre>
        </div>
      </div>

      <div class="test-section">
        <h4>游戏娱乐API测试</h4>
        <van-button type="primary" @click="testGameAPI" :loading="testing.game">
          测试游戏娱乐
        </van-button>
        <div v-if="results.game" class="test-result">
          <pre>{{ results.game }}</pre>
        </div>
      </div>

      <div class="test-section">
        <h4>环境信息</h4>
        <div class="env-info">
          <p><strong>当前环境:</strong> {{ import.meta.env.MODE }}</p>
          <p><strong>API Base URL:</strong> {{ import.meta.env.VITE_API_BASE_URL || '未设置' }}</p>
          <p><strong>当前域名:</strong> {{ window.location.origin }}</p>
          <p><strong>用户ID:</strong> {{ getCurrentUserId() || '未登录' }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { showToast } from 'vant'
import aiService from '@/services/aiService'
import { getCurrentUserId } from '@/utils/userDataManager'

const testQuestion = ref('你好，这是一个测试问题')

const testing = ref({
  basic: false,
  qa: false,
  stream: false,
  game: false
})

const results = ref({
  basic: '',
  qa: '',
  stream: '',
  game: ''
})

// 测试基础连接
const testBasicConnection = async () => {
  testing.value.basic = true
  try {
    console.log('🔗 开始基础连接测试...')

    // 测试多个端点
    const endpoints = ['/api/health', '/api/test', '/api/ai/test']
    const testResults = []

    for (const endpoint of endpoints) {
      try {
        console.log(`测试端点: ${endpoint}`)
        const response = await fetch(endpoint, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          }
        })

        testResults.push({
          endpoint,
          status: response.status,
          statusText: response.statusText,
          ok: response.ok,
          body: await response.text()
        })
      } catch (error) {
        testResults.push({
          endpoint,
          error: error.message || error.toString()
        })
      }
    }

    results.value.basic = JSON.stringify({
      timestamp: new Date().toISOString(),
      baseUrl: window.location.origin,
      results: testResults
    }, null, 2)

    showToast('基础连接测试完成')
  } catch (error) {
    results.value.basic = `错误: ${error}`
    showToast('基础连接测试失败')
  } finally {
    testing.value.basic = false
  }
}

// 测试知识问答API
const testKnowledgeQA = async () => {
  testing.value.qa = true
  try {
    console.log('开始测试知识问答API...')
    const response = await aiService.knowledgeQA(12345, testQuestion.value)

    const result = {
      timestamp: new Date().toISOString(),
      request: {
        userId: 12345,
        question: testQuestion.value
      },
      response: response
    }

    results.value.qa = JSON.stringify(result, null, 2)
    showToast('知识问答API测试完成')
  } catch (error) {
    const errorResult = {
      timestamp: new Date().toISOString(),
      error: error.toString(),
      stack: error.stack,
      message: error.message
    }
    results.value.qa = JSON.stringify(errorResult, null, 2)
    showToast('知识问答API测试失败')
  } finally {
    testing.value.qa = false
  }
}

// 测试流式API
const testStreamAPI = async () => {
  testing.value.stream = true
  let streamResult = ''
  let messageCount = 0

  try {
    console.log('🌊 开始测试流式API...')
    results.value.stream = '正在连接流式API...'

    await aiService.knowledgeQAStream(
      12345,
      testQuestion.value,
      // onMessage
      (content: string) => {
        messageCount++
        streamResult += content
        console.log(`📝 收到第${messageCount}条流式消息:`, content)
        results.value.stream = `流式内容 (${messageCount}条消息):\n${streamResult}\n\n状态: 接收中...`
      },
      // onComplete
      () => {
        console.log('✅ 流式API测试完成')
        results.value.stream = `流式内容 (共${messageCount}条消息):\n${streamResult}\n\n状态: ✅ 完成\n最终长度: ${streamResult.length}字符`
        showToast('流式API测试完成')
        testing.value.stream = false
      },
      // onError
      (error: any) => {
        console.error('❌ 流式API错误:', error)
        results.value.stream = `流式API错误:\n类型: ${typeof error}\n消息: ${error.message || error}\n详情: ${JSON.stringify(error, null, 2)}`
        showToast('流式API测试失败')
        testing.value.stream = false
      }
    )
  } catch (error) {
    console.error('❌ 流式API异常:', error)
    const errorResult = {
      timestamp: new Date().toISOString(),
      error: error.toString(),
      stack: error.stack,
      message: error.message,
      name: error.name
    }
    results.value.stream = `流式API异常:\n${JSON.stringify(errorResult, null, 2)}`
    showToast('流式API测试异常')
    testing.value.stream = false
  }
}

// 测试游戏娱乐API
const testGameAPI = async () => {
  testing.value.game = true
  let streamResult = ''
  let messageCount = 0

  try {
    console.log('🎮 开始测试游戏娱乐API...')
    results.value.game = '正在连接游戏API...'

    // 测试流式游戏API
    await aiService.gameEntertainmentStream(
      12345,
      'riddle',
      '开始游戏',
      'start',
      'easy',
      5,
      true,
      false,
      // onMessage
      (content: string) => {
        messageCount++
        streamResult += content
        console.log(`🎯 收到第${messageCount}条游戏消息:`, content)
        results.value.game = `游戏内容 (${messageCount}条消息):\n${streamResult}\n\n状态: 接收中...`
      },
      // onComplete
      () => {
        console.log('✅ 游戏流式API测试完成')
        results.value.game = `游戏内容 (共${messageCount}条消息):\n${streamResult}\n\n状态: ✅ 完成\n最终长度: ${streamResult.length}字符`
        showToast('游戏API测试完成')
        testing.value.game = false
      },
      // onError
      async (error: any) => {
        console.error('❌ 游戏流式API错误:', error)

        // 尝试非流式API
        try {
          const response = await aiService.gameEntertainment(12345, 'riddle', '开始游戏', 'start', 'easy', 5, true, false)
          console.log('📊 非流式游戏API响应:', response)

          const result = {
            timestamp: new Date().toISOString(),
            streamError: error.toString(),
            fallbackResponse: response
          }

          results.value.game = `游戏API测试结果:\n${JSON.stringify(result, null, 2)}`
          showToast('游戏API测试完成（降级）')
        } catch (fallbackError) {
          const errorResult = {
            timestamp: new Date().toISOString(),
            streamError: error.toString(),
            fallbackError: fallbackError.toString()
          }
          results.value.game = `游戏API错误:\n${JSON.stringify(errorResult, null, 2)}`
          showToast('游戏API测试失败')
        }

        testing.value.game = false
      }
    )
  } catch (error) {
    console.error('❌ 游戏API异常:', error)
    const errorResult = {
      timestamp: new Date().toISOString(),
      error: error.toString(),
      stack: error.stack,
      message: error.message,
      name: error.name
    }
    results.value.game = `游戏API异常:\n${JSON.stringify(errorResult, null, 2)}`
    showToast('游戏API测试异常')
    testing.value.game = false
  }
}
</script>

<style scoped>
.api-test-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.test-container {
  padding: 16px;
}

.test-section {
  margin-bottom: 24px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.test-section h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.test-result {
  margin-top: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e9ecef;
  max-height: 300px;
  overflow-y: auto;
}

.test-result pre {
  margin: 0;
  font-size: 12px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-break: break-all;
}

.env-info {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.env-info p {
  margin: 4px 0;
  font-size: 14px;
}

.van-button {
  margin-bottom: 12px;
}
</style>
